import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import classnames from 'classnames';
import QueueAnim from 'rc-queue-anim';

import { Button, List, Bubble, Tools, DatePicker } from 'weaver-mobile';
import { Form, RouteLayout, SelectPage } from 'weaver-mobile-page';

const getLabel = Tools.getLabel;

@inject('todoStore')
@withRouter
@observer
export default class SetTodo extends Component {
  static defaultProps = {
    prefixCls: 'email-todo-set',
  }

  componentDidMount() {
    const { path, params, todoStore: { doInit } } = this.props;
    doInit(path, params);
  }

  componentWillUnmount() {
    const { todoStore: { setState } } = this.props;
    setState({selectArr: []})
  }

  submit = () => {
    const { onSubmit, params: { mailId }, todoStore: { addOrUpdateWaitDeal, form } } = this.props;
    const { formParams } = form;
    const { waitdealtime, wdremindtime, op_hasNote, waitdealnote, op_hasRemind, waitdealway} = formParams;
    if (waitdealtime === '') {
      Bubble.error(getLabel('504599','"处理时间" 未填写'), 1);
      return;
    } else if (op_hasRemind === 1 && wdremindtime === '') {
      Bubble.error(getLabel('504602','"提醒时间" 未填写'), 1);
      return;
    } else if (op_hasRemind === 1 && waitdealway === '') {
      Bubble.error(getLabel(513621, '"提醒方式"未选择'), 1);
      return;
    } else if (op_hasNote === 1 && waitdealnote.trim() === '') {
      Bubble.error(getLabel('504603','"备注" 未填写'), 1);
      return;
    }
    addOrUpdateWaitDeal(mailId, () => {
      if (onSubmit) onSubmit(formParams); // 提交时候的回调
    });
  }

  formatDate = (time, str) => {
    let obj = {
      yyyy: time.getFullYear(),
      MM: ('0' + (time.getMonth() + 1)).slice(-2),
      dd: ('0' + time.getDate()).slice(-2),
      HH: ('0' + time.getHours()).slice(-2),
      mm: ('0' + time.getMinutes()).slice(-2),
    }
    return str.replace(/([a-z]+)/ig, v => obj[v])
  }

  setRmMaxTime = (date) => {
    const newDate = this.formatDate(new Date, 'yyyy-MM-dd')
    if (date) {
      if (date === newDate) {
        return `${date} 23:59`
      }
      return date;
    }
  }

  getFields = (form, conditions) => {
    const { todoStore: { selectPage, selectArr, setState } } = this.props;
    const { isInit, formParams : { op_hasNote, op_hasRemind, waitdealtime, wdremindtime } } = form;
    const fields = [];
    const remindMaxTime = this.setRmMaxTime(waitdealtime);
    if (isInit) {
      toJS(conditions).forEach((group) => {
        group.items.forEach((field) => {
          if (field.domkey[0] === 'waitdealway' && op_hasRemind !== 1) {
            return;
          }
          if (field.domkey[0] === 'wdremindtime' && op_hasRemind !== 1) {
            return;
          }
          if (field.domkey[0] === 'waitdealnote' && op_hasNote !== 1) {
            return;
          }
          if (field.domkey[0] === 'waitdealway') {
            fields.push(
              <SelectPage
                store={selectPage}
                options={field.options}
                label={field.label}
                valueArray={selectArr}
                onChange={datas => {
                  let arr = [];
                  datas.map((v) => {
                    arr.push(v.key);
                  });
                  setState({ selectArr: arr });
                  form.updateField('waitdealway', arr);
                }}
                viewAttr='3'
                multiChoose
              />
            )
          } else if (field.domkey[0] === 'waitdealtime') {
            fields.push(
              <DatePicker
                mode={'date'}
                value={waitdealtime || ''}
                minDate={wdremindtime ? wdremindtime : new Date}
                onOk={val => {
                  let chooseTime = this.formatDate(val, 'yyyy-MM-dd')
                  form.updateField('waitdealtime', chooseTime);
                }}
                onClear={() => form.updateField('waitdealtime', '')}
              >
                <List.Item arrow="horizontal"><span style={{paddingLeft: 7, color: '#333'}}>{field.label}</span></List.Item>
              </DatePicker>
            )
          } else if (field.domkey[0] === 'wdremindtime') {
            fields.push(
              <DatePicker
                value={wdremindtime || ''}
                minDate={this.formatDate(new Date, 'yyyy-MM-dd HH:mm')}
                maxDate={remindMaxTime || ''}
                onOk={val => {
                  let chooseTime = this.formatDate(val, 'yyyy-MM-dd HH:mm')
                  form.updateField('wdremindtime', chooseTime);
                }}
                onClear={() => form.updateField('wdremindtime', '')}
              >
                <List.Item arrow="horizontal"><span style={{paddingLeft: 7, color: '#333'}}>{field.label}</span></List.Item>
              </DatePicker>
            )
          } else {
            fields.push(<Form.Item
              key={field.domkey.join('__')}
              form={form}
              fieldConfig={field}
              onChange={(...arg) => {
                const { domkey } = arg[0];
                const key = domkey[0];
                const value = arg[1];
                form.onChange(...arg);
                if (key === 'op_hasRemind' && value === 0) {
                 form.updateField('wdremindtime', '');
                 form.updateField('waitdealway', '5');
                 setState({ selectArr: ['5'] });
                }
                if (key === 'op_hasNote' && value === 0) {
                 form.updateField('waitdealnote', '');
                }
              }}
            />);
          }
        });
      });
    }
    return fields;
  }
 
  render() {
    const { prefixCls, todoStore: { form, condition } } = this.props;
    const cls = classnames('wm-route-layout', prefixCls);

    return (
      <RouteLayout>
        <div key="todo" className={cls}>
          <Form store={form}>
            <List>
              <QueueAnim
                style={{overflowX: 'hidden'}}
              >
                {form && this.getFields(form, condition)}
              </QueueAnim>
            </List>
          </Form>
          <Button type="primary" onClick={this.submit}>{getLabel('30986','保存')}</Button>
        </div>
      </RouteLayout>
    );
  }
}